package io.github.mymonstercat.utils;

import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.Objects;

@Slf4j
public class HwOCRUtils {

    public static final String API_HOST = "http://10.40.39.73:32001/";

    private static final int MAX_RETRIES = 3;  // 最大重试次数

    public static String recognizeGeneralText(String filePath) throws Exception {
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        String base64 = convertImageToBase64(filePath);
        String json = "{\"image\":\"" + base64 + "\",  \"detect_direction\":false,  \"quick_mode\":false }";
        MediaType mediaType = MediaType.get("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(mediaType, json);
        Request request = new Request.Builder().url(API_HOST + "v2/123/ocr/general-text")
                .method("POST", body)
                .addHeader("User-Agent", "Apifox/1.0.0 (https://apifox.com)")
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "*/*")
                .addHeader("Host", "10.40.39.73:32001")
                .addHeader("Connection", "keep-alive")
                .build();

        // 尝试重试逻辑
        int attempt = 0;
        Response response = null;
        String responseBodyStr = null;
        while (attempt < MAX_RETRIES) {
            try {
                response = client.newCall(request).execute();
                if (response.isSuccessful()) {
                    // 在关闭响应之前，先获取响应体内容
                    responseBodyStr = Objects.requireNonNull(response.body()).string();
                    return responseBodyStr;  // 返回响应体内容
                } else {
                    log.info("华为OCR请求失败第" + attempt + "次");
                }
            } catch (IOException e) {
                log.info("华为OCR请求失败第" + attempt + "次" + e.getMessage());
            } finally {
                if (response != null) {
                    response.close();  // 确保关闭响应体
                }
            }

            attempt++;
            log.info("Retrying... Attempt: " + attempt);

            // 如果尝试次数已达到最大值
            if (attempt >= MAX_RETRIES) {
                throw new IOException("Failed to get response from Huawei OCR after " + MAX_RETRIES + " attempts.");
            }
        }

        return responseBodyStr;  // 理论上这里不会被执行
    }



    public static String convertImageToBase64(String imagePath) {
        byte[] imageBytes = null;
        try {
            // 读取图片文件
            imageBytes = Files.readAllBytes(Paths.get(imagePath));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        // 将字节数组转换为 Base64 编码的字符串
        String base64Image = Base64.getEncoder().encodeToString(imageBytes);
        return base64Image;
    }

//    public static void main(String[] args) throws Exception {
//        String s = HwOCRUtils.recognizeGeneralText("D:\\home\\images\\page_0.png");
//        System.out.println(s);
//    }

}
